package com.qmock.pay.umpay;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author tianqing.wang
 */
public class UmpayStringUtils {
    /**通过给map排序并且给数组签名生成响应的数据信息。参数信息来自于签名请求的参数*/
    public static String toString(Map<String,String> stringMap){
        StringBuilder stringBuilder=new StringBuilder();
        //stringBuilder.append("<META NAME=\"MobilePayPlatform\"");
        //stringBuilder.append("CONTENT=\" ");
        if(stringMap.size()==0){
            throw new RuntimeException("传递的响应请求参数组合为空，请检查是否设置参数。");
        }
        int i=0;
        for(Map.Entry<String,String> entry:stringMap.entrySet()){
            String key = entry.getKey();
            String value = entry.getValue();
            if(i<stringMap.size()-1){
                stringBuilder.append(key+"="+value+"&");
            }else{
                stringBuilder.append(key+"="+value);
            }
            i++;
        }
       // stringBuilder.append("\">");
        return stringBuilder.toString();
    }

    /**
     * @param  stringMap 请求的参数对
     * @return 返回需要签名的字符串
     * */
    public static String toSignString(Map<String,String> stringMap) {
        boolean isContainsAny=false;
        List<String> keys = new ArrayList<String>(stringMap.keySet());
        Collections.sort(keys);
        StringBuilder signSource = new StringBuilder(64);
        for (int i = 0; i < keys.size(); i++) {
            String key = (String) keys.get(i);
            if ("sign".equals(key) || "sign_type".equals(key)) {// 做签名不需要这两个字段
                continue;
            }
            String value = stringMap.get(key);
            if(null==value||"".equals(value)){
                continue;
            }
            if (i > 0) {
                signSource.append("&").append(key).append("=").append(value);
            } else {
                signSource.append(key).append("=").append(value);
            }
        }
        return signSource.toString();
    }
}
